import 'package:get/get.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'package:pass_log/app/data/providers/type_provider.dart';
import 'package:pass_log/app/data/providers/pass_provider.dart';

typedef ObjItem = Map<String, dynamic>;

class HomeController extends GetxController {
  var typeList = Get.find<TypeListProvider>().list;
  var passList = Get.find<PassListProvider>().list;
  var mainList = <ObjItem>[].obs;
  var searchQuery = "".obs;
  var isSearching = false.obs;
  var searchList = <ObjItem?>[].obs;

  // 刷新主列表
  void refreshMainList() {
    // 创建一个哈希表来根据 type_id 组织密码列表
    var passMap = <dynamic, List<ObjItem>>{};
    for (var pass in passList) {
      var typeId = pass?["type_id"];
      if (pass == null || typeId == null) continue;
      if (!passMap.containsKey(typeId)) {
        passMap[typeId] = [];
      }
      passMap[typeId]!.add(pass);
    }
    // 构建最终的渲染列表
    var list = <ObjItem>[];
    for (var type in typeList) {
      var typeId = type["id"];
      var children = passMap[typeId] ?? [];
      list.add({...type, "children": children});
    }
    mainList.value = list;
  }

  // 搜索密码
  void searchPass(String query) {
    if (query.isEmpty) {
      searchList.value = <ObjItem?>[];
    } else {
      var lowerQuery = query.toLowerCase();
      var result = passList
          .where((item) => item != null && (item["title"] as String).toLowerCase().contains(lowerQuery));
      searchList.value = result.toList();
    }
  }

  @override
  void onInit() async {
    super.onInit();
    refreshMainList();
    EasyLoading.instance
      ..dismissOnTap = false // 点击背景时不会关闭loading
      ..userInteractions = false // 展示loading时禁止用户操作
      ..toastPosition = EasyLoadingToastPosition.bottom
      ..displayDuration = const Duration(milliseconds: 500);
    // 防抖：搜索密码
    debounce(searchQuery, searchPass, time: const Duration(milliseconds: 500));
  }
}
